package com.cnfangmao.masterdata.shiro;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import com.cnfangmao.masterdata.common.util.SpringUtil;
import com.cnfangmao.masterdata.common.util.UserUtils;
import com.cnfangmao.masterdata.dao.PermissionDao;
import com.cnfangmao.masterdata.dao.RoleDao;
import com.cnfangmao.masterdata.model.Account;
import com.cnfangmao.masterdata.model.Permission;
import com.cnfangmao.masterdata.model.Role;
import com.cnfangmao.masterdata.service.AccountService;

public class MyShiroRealm  extends AuthorizingRealm{
	
	@Autowired
	private AccountService accountService;

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) {
		
		System.out.println("执行了=>授权 doGetAuthorizationInfo");
		//给用户授予权限
		SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
		
		//拿到当前登录得这个对象
		Subject subjcet = SecurityUtils.getSubject();
		
		//拿到User对象
		Object currentUser =  subjcet.getPrincipal(); //从认证方法中 return SimpleAuthenticationInfo(第一个参数) 拿到得当前用户对象
		Account account =(Account)currentUser;
		
		//获取角色
		List<Role> roles = SpringUtil.getBean(RoleDao.class).listByUserId(account.getUserId());
		Set<String> roleCodes = roles.stream().map(Role::getRoleCode).collect(Collectors.toSet());
		authorizationInfo.setRoles(roleCodes);
		
		//获取权限
		List<Permission> permissionList = SpringUtil.getBean(PermissionDao.class).listPermissionByUserId(account.getUserId());
		UserUtils.setPermissionSession(permissionList);
		Set<String> permissioncodes = permissionList.stream().map(Permission::getPermissionCode).collect(Collectors.toSet());
		authorizationInfo.setStringPermissions(permissioncodes);

		return authorizationInfo;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        
        //加这一步的目的是在Post请求的时候会先进认证，然后在到请求
        if (token.getPrincipal() == null) {
            return null;
        }
        
        //获取用户信息
        String userCode = token.getPrincipal().toString();
        Account userInfo = accountService.findByUserCode(userCode);
        if (userInfo == null) {
            //这里返回后会报出对应异常
            return null;
        } else {
//            //这里验证authenticationToken和simpleAuthenticationInfo的信息
           
        	return new SimpleAuthenticationInfo(userInfo,userInfo.getPassword(),this.getName());
        }
	}

}
